using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NCS.Library;
using NCS.Library.Components.Portal;
using NCS.Library.Components.Roles;
using NCS.Library.Components.Security;
using NCS.Library.Components.Users;
using NCS.Library.Utilities;

namespace Portal.Administrator.Roles
{
	public partial class UserInRole : AuthenticatedControl
	{
		private int roleId;
		protected void Page_Load(object sender, EventArgs e)
		{
			roleId = ConvertUtility.ToInt32(Request.QueryString["roleid"]);
            if (roleId == 34) this.Visible = false;
			if (!Page.IsPostBack)
			{
				RoleInfo role = RoleController.GetRole(roleId);
				if (role == null)
				{
					this.btnAdd.Visible = false;
					this.btnRemove.Visible = false;
					return;
				}
				lblRoleName.Text = role.RoleName;

                dropPortal.Items.Clear();
                if (!CurrentUser.IsSuperAdmin && !CurrentUser.IsAdmin)
                {
                    PortalController.LoadPortalsForUserID(dropPortal.Items, CurrentUser.UserID);
                }
                else
                {
                    PortalController.LoadPortals(dropPortal.Items);
                }
			}

		}
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			//lstUsers.DataSource = UserController.GetUsersNotInRole(AppEnv.DEFAULT_ROLE, ConvertUtility.ToInt32(dropPortal.SelectedValue));
            lstUsers.DataSource = UserController.GetUsersNotInRole(roleId, ConvertUtility.ToInt32(dropPortal.SelectedValue));
			lstUsers.DataBind();

            lstUserInRole.DataSource = UserController.GetUsers(roleId, ConvertUtility.ToInt32(dropPortal.SelectedValue));
			lstUserInRole.DataBind();
		}
		protected void btnAdd_Click(object sender, EventArgs e)
		{
			foreach (ListItem item in lstUsers.Items)
			{
				if (item.Selected)
				{
                    RoleController.UpdateUserToRole(Convert.ToInt32(item.Value), roleId, ConvertUtility.ToInt32(dropPortal.SelectedValue));
                    this.AddLog("User in Role", " try add user " + item.Value + " to role " + roleId + " in portal " + dropPortal.SelectedValue);
				}
			}
		}
		protected void btnRemove_Click(object sender, EventArgs e)
		{
			foreach (ListItem item in lstUserInRole.Items)
			{
				if (item.Selected)
				{
					RoleController.RemoveUserFromRole(Convert.ToInt32(item.Value), AppEnv.DEFAULT_ROLE, ConvertUtility.ToInt32(dropPortal.SelectedValue));
                    this.AddLog("User in Role", " try remove user " + item.Value + " to role " + roleId + " in portal " + dropPortal.SelectedValue);
				}
			}
		}

        protected void dropPortal_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }
	}
}